package com.dagger.config;

import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import com.alibaba.fastjson2.JSON;
import com.dagger.constant.MessageConstants;
import com.dagger.utils.AbstractMsgUtil;
import com.dagger.vo.RealtimeMsgVo;

import lombok.extern.slf4j.Slf4j;

/**
 * redis轻量实时消息发布订阅配置
 * 
 * @author dagger
 *
 */
@Slf4j
@Configuration
@AutoConfigureBefore({ RedisAutoConfiguration.class })
public class RedisMsgConfig {
	@Bean
	MessageListenerAdapter messageListener() {
		return new MessageListenerAdapter(new RealtimeMsgSubcribe());
	}

	@Bean
	RedisMessageListenerContainer redisContainer(RedisConnectionFactory factory) {
		final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(factory);
		container.addMessageListener(messageListener(), new ChannelTopic(MessageConstants.MSG_REALTIME_CHANNEL));
		return container;
	}

	/**
	 * 实时消息订阅
	 * 
	 * @author dagger
	 *
	 */
	class RealtimeMsgSubcribe implements MessageListener {
		@Override
		public void onMessage(Message message, byte[] bytes) {
			FastJson2JsonRedisSerializer<RealtimeMsgVo> serializer = new FastJson2JsonRedisSerializer<>(RealtimeMsgVo.class);
			RealtimeMsgVo deserialize = serializer.deserialize(message.getBody());;
			log.info("received realtime msg bussinessType = {}", deserialize.getBussinessType());
			log.info("received realtime msg bussinessId = {}", deserialize.getBussinessId());
			log.info("received realtime msg msgContent: {}", JSON.toJSONString(deserialize.getMsgContent()));
			AbstractMsgUtil.sendRealtimeMessage(deserialize.getBussinessType(), deserialize.getBussinessId(), deserialize.getMsgContent());
		}
	}
}